package com.atguigu.gmall.product.contioller;

import com.atguigu.gmall.common.result.Result;
import org.apache.commons.io.FilenameUtils;
import org.csource.common.MyException;
import org.csource.fastdfs.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * description:
 * create by sxy 2021/5/10
 */
@RestController
@RequestMapping("/admin/product")
public class FileUploadController {

    @Value("${image.url}")
    private String imageUrl;

    @PostMapping("/fileUpload")
    public Result fileUpload(MultipartFile file) throws IOException, MyException {
        String path = ClassUtils.getDefaultClassLoader().
                getResource("fdfs_client.conf").getPath();
        //0 配置跟踪器的ip port
        ClientGlobal.init(path);
        //创建traxkerclient客户端
        TrackerClient trackerClient = new TrackerClient();

        //2连接trackerserver端
        TrackerServer trackerServer = null;
        try {
            trackerServer = trackerClient.getConnection();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //3创建storage客户端
        StorageServer storageServer = null;
        StorageClient1 storageClient1 = new StorageClient1(trackerServer, storageServer);

        //3 上传文件
        String fileId = null;
        try {
            String extension = FilenameUtils.getExtension(file.getOriginalFilename());

            fileId = storageClient1.upload_file1(
                    file.getBytes(), extension, null);
            System.out.println(imageUrl + fileId);
            return Result.ok(imageUrl + fileId);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MyException e) {
            e.printStackTrace();
        }

        //http://192.168.6.131:8080/group1/M00/00/00/wKgGg2CZRmOAFOYFABb6is_KHqs871.jpg

        return null;
    }
}
